// pages/mine/mine.js
const {
  getBarAndTitleHeight,
  jump,
  getStorage,
  setStorage,
} = require('../../utils/utils.js')
import api from '../../config/api'
import {
  getUserLocation,
  getUserPermissions,
  shareOptions,
} from '../../utils/access'
import request from '../../utils/request'
const app = getApp()

Page({
  data: {
    ADkey:'',
    // 未登录信息
    noLoginInfo: {
      avatarUrl:
        'https://image-classify.daieco.com/kejian-quanzi/9uUvCOD8Ovlu8c6962a1738808eef6eed26d9ec37d7d.png',
      nickName: '注册/登录',
    },
    // 用户信息
    userInfo: {
      avatarUrl: '',
      nickName: '',
    },
    // 服务列表
    serviceList: [
      {
        title: '圈子',
        subtitle: '垃圾分类交流圈',
        color: '#6E9A22',
        infoList: [
          {
            start: '',
            end: ' 人参与',
          },
        ],
        path: 'circleHome',
        url: 'https://image-classify.daieco.com/kejian-space/M8ty0YYQjwvb167f717f98b1452ff187d733218255af.png',
      },
      
      {
        title: '挑战',
        subtitle: '21天习惯养成',
        color: '#FF9101',
        infoList: [
          {
            start: '',
            end: '人参与该挑战',
          },
        ],
        path: 'trophy',
        url: 'https://image-classify.daieco.com/kejian-space/0jqPfzhsuApHf686b7faf15314cac55a1ed6343d9c09.png',
      },
      
      {
        title: '成就',
        subtitle: '垃圾分类排行榜',
        color: '#439AFF',
        infoList: [
          {
            start: '本周排名 ',
            end: '',
          },
        ],
        path: 'medal',
        url: 'https://image-classify.daieco.com/kejian-space/JEhNquH3Cp6v12c8f75399c59b49696d584a1d96ab2b.png',
      },
      {
        title: '闲置',
        subtitle: '身边的二手平台',
        color: '#9C52D7',
        infoList: [
          {
            start: '共有',
            end: '件商品',
          },
        ],
        path: 'fawnIdleHome',
        url: 'https://image-classify.daieco.com/kejian-space/fj5sLXUUuW6bc9d39c77324888da4086250289e30a90.png',
      },
      // {
      // 	title: '收纳',
      // 	subtitle: '相信空间的力量',
      // 	color: '#439AFF',
      // 	infoList: [
      // 		{ start: '收纳 ', end: ' 件' }
      // 	],
      // 	path: 'acceptStorageIndex',
      // 	url: 'https://image-classify.daieco.com/kejian-space/gSQPjViIJwE1bf2d634d539c891cb9ddfa83935b7273.png'
      // },
    ],
    // 状态栏&标题栏高度
    ...getBarAndTitleHeight(true),
    // 是否有登录
    isLogin: false,
    // 用户信息
    userData: {},
    // 用户消息数量
    notice: 0,
    addressInfo: {
      latitude: '',
      longitude: '',
    },
    // 是否是测试环境
    isDev: false,
    // 用户身份依据 1:普通用户 2:督导员
    userIdentity: 2,
    // 碳减排的单位
    unit: 'g',
    //小程序跳转
    loadMiniProgram: false,
    // 是否是目标小区
    isTargetCommunity: false,
    // 联系我们-整体二维码
    serviceQrcode:
      'https://image-classify.daieco.com/kejian-quanzi/mrm4Z9LEuSF514052d3cebf4e5fff095132b1eb81863.png',
    // 单独二维码
    qrcode:
      'https://image-classify.daieco.com/kejian-quanzi/Iwh5x26q9vzA8a6cd3e1aacd48a9a17f14cd314cd7fb.png',
    // 未查看兑换券数量
    couponNum: 0,
    // 页面滚动高度
    scrollTop: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取用户身份类型
    const userIdentity = getStorage('userIdentity')
    let { barHeight, titleHeight } = getBarAndTitleHeight()
    this.setData({
      ...getBarAndTitleHeight(),
      isDev: !api.authSwap.startsWith('https'),
      userIdentity: userIdentity,
      scrollHeight: barHeight+titleHeight+40
    })
    console.log(this.data.userIdentity)

  },

  adError(err){
		const { errMsg = '', errCode = '' } = err.detail || {}
		console.log(`广告加载失败: [${errCode}]${errMsg}`);
    this.setData({
			ADkey:''
		})
	},

  	// 获取广告数据
	async getADData(){
		const res = await request.get(api.getAdShowData)
		console.log('guanggao',res);
		if(res.httpStatus===200){
			let item = res.data.find((item)=>{
				return item.advertSpace===2
			})
			console.log('item',item);
			this.setData({
				ADkey:item?item.advertId:''
			})
		}
	},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const userIdentity = getStorage('userIdentity')

    // 判断是否展示优惠券红点
    let newCouponNum = getStorage('newCouponNum')
    let newMsgNum = getStorage('newMsgNum')
    if (!newCouponNum) {
      this.handleShowCoupon()
    }
    if (!newMsgNum) {
      this.handleShowMessage()
    }

    this.getTabBar?.()?.setData?.({
      selected: 4,
      newMsgNum: newMsgNum ? newMsgNum : 0,
    })
    // 设置是否是目标小区
    app.checkIsTarget((isTargetCommunity) => {
      this.setData({
        isTargetCommunity,
      })
      this.getTabBar?.()?.setData?.({
        isTargetCommunity,
      })
    })
    this.getChallengeStatus()

    this.setData({
      userInfo: app.isLogin() ? app.userInfo() : this.data.noLoginInfo,
      isLogin: app.isLogin(),
      userIdentity: userIdentity,
      userData: {},
    })
    this.getInfo()

    this.setData({
      couponNum: newCouponNum,
    })

    this.getADData()
  },
  // 是否展示消息红点
  async handleShowMessage() {
    const res = await request.get(
      api.isShowMessage,
      {},
      {
        loading: false,
        modal: false,
      }
    )
    if (res.httpStatus === 200) {
      if (res.data) {
        setStorage('newMsgNum', 1)
        this.getTabBar?.()?.setData?.({
          newMsgNum: 1,
        })
      }
    }
  },
  // 是否展示优惠券红点
  async handleShowCoupon() {
    const res = await request.get(
      api.isShowCoupon,
      {},
      {
        loading: false,
        modal: false,
      }
    )
    if (res.httpStatus === 200) {
      if (res.data) {
        setStorage('newCouponNum', 1)
        this.setData({
          couponNum: 1,
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.modal = this.selectComponent('#modal')
    this.serviceModal = this.selectComponent('#serviceModal')
  },

  /**
   * 用户登录
   */
  async login() {
    if (!this.data.isLogin) {
      setStorage('redirectPath', '/pages/mine/mine')
      const userInfo = await app.login()
      this.setData({
        userInfo,
        isLogin: app.isLogin(),
      })
    } else {
      wx.navigateTo({
        url: '/pages/home/home?id=' + getStorage('userId'),
      })
    }
  },

  /**
   * 点击tab选项
   */
  async handleClick(e) {
    const {
      dataset: { path = '', status = '', id = '' },
    } = e?.currentTarget

    if (app.isLogin()) {
      if (path === 'trophy' && status !== 1) {
        if (status) {
          this.modal.show()
        }
        return
      }
      if (path === 'idleHome') {
        // 判断定位权限是否打开
        if (!getUserLocation()) {
          getUserPermissions('userLocation', (res) => {
            if (res) {
              jump(path)
            }
          })
          return
        }
      }
      jump(path)
    } else {
      setStorage('redirectPath', '/pages/mine/mine')
      const userInfo = await app.login(e?.detail)
      this.setData({
        userInfo,
        isLogin: app.isLogin(),
      })
    }
  },
  // 开启挑战
  async confirm(e) {
    await request.get(api.startChallenge, null, {
      loading: false,
    })
    e.detail.hide()
    jump('trophy')
  },
  // 获取用户挑战状态&圈子列表
  async getChallengeStatus() {
    let { serviceList } = this.data
    const res = await request.get(api.challengeCircle, null, {
      loading: false,
    })
    const goods = await request.get(api.getUserGoodsSum, null, {
      loading: false,
    })

    const [challengeData] = res?.data?.challengeList || []
    if (challengeData) {
      const trophyIndex = serviceList.findIndex((f) => f.title === '挑战')
      serviceList[trophyIndex].subtitle = challengeData?.description
      serviceList[trophyIndex].status = challengeData?.taskStatus
      serviceList[trophyIndex].infoList[0].value = challengeData?.joinNum
    }

    const circleData = res?.data?.adminSocialCircleAllVO || {}
    if (circleData) {
      const circleIndex = serviceList.findIndex((f) => f.title === '圈子')
      serviceList[circleIndex].id = circleData?.id
      serviceList[circleIndex].infoList[0].value = circleData?.partakeUserNumber
    }

    // const goodsIndex = serviceList.findIndex(f => f.title === '收纳')
    // serviceList[goodsIndex].infoList[0].value = goods?.data || 0

    this.setData({
      serviceList,
    })
  },
  // 获取用户信息
  async getInfo() {
    const userId = getStorage('userId')
    if (userId) {
      this.getNotice()
      const res = await request.get(
        api.homeDetail,
        {
          userId,
        },
        {
          loading: false,
          modal: false,
        }
      )
      if (res.httpStatus !== 200) {
        this.setData({
          userInfo: {
            ...this.data.noLoginInfo,
          },
          isLogin: app.isLogin(),
        })
        return
      }
      let serviceIdleValue = 'serviceList[3].infoList[0].value'
      //新增小区信息
      setStorage('communityBind', res?.data.communityBind || false)
      setStorage('communityName', res?.data.communityName || ' ')
      setStorage('communityCode', res?.data.communityId || ' ')
      console.log(res.data)
      // 判断碳减排的值是否超过1000 超过1000 由g转换为kg
      if (res.data.carbonEmissionNum >= 1000) {
        res.data.carbonEmissionNum = res.data.carbonEmissionNum / 1000
        // 保留2位小数,不进行四舍五入
        res.data.carbonEmissionNum = res.data.carbonEmissionNum
          .toString()
          .match(/^\d+(?:\.\d{0,2})?/)
        console.log(res.data.carbonEmissionNum)
        res.data.carbonEmissionNum = parseFloat(res.data.carbonEmissionNum[0])
        console.log(res.data.carbonEmissionNum)
        this.setData({
          unit: 'kg',
        })
      }
      this.setData({
        userData: {
          ...res?.data,
        },
        [serviceIdleValue]: res?.data.goodsSum,
      })
    }
  },
  // 获取用户消息数量
  async getNotice() {
    if (app.isLogin()) {
      const res = await request.get(api.noticeCount, null, {
        loading: false,
        modal: false,
      })
      if (res.httpStatus === 200) {
        const noticeCount = res?.data?.allNumber

        this.setData({
          notice: noticeCount > 99 ? '99+' : noticeCount,
        })
      } else {
        this.setData({
          userInfo: {
            ...this.data.noLoginInfo,
          },
          isLogin: app.isLogin(),
        })
      }
    }
  },
  /**
   * 查看图片
   */
  handlePreview() {
    const { qrcode } = this.data
    wx.previewImage({
      current: qrcode,
      urls: [qrcode],
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      userInfo: app.isLogin() ? app.userInfo() : this.data.noLoginInfo,
    })
    this.getChallengeStatus()
    this.getInfo()
    wx.stopPullDownRefresh()
  },
  // 跳转需要登录页面
  async jumpPageNeedLogin(event) {
    const dataset = event.currentTarget.dataset
    const url = dataset.path
    if (app.isLogin()) {
      if (url) {
        jump(url, {
          ...dataset?.params?.[0],
        })
      }
    } else {
      setStorage('redirectPath', '/pages/mine/mine')
      const userInfo = await app.login()
      this.setData({
        userInfo,
        isLogin: app.isLogin(),
      })
    }
  },
  // 跳转不需要登录页面
  jumpPageNoLogin(event) {
    const url = event.currentTarget.dataset.path
    if (url) {
      jump(url)
    }
  },
  async jumpRecycle() {
    if (app.isLogin()) {
      //通过接口判断是否是代代回收用户
      const res = await request.get(api.getRecycleQR)

      if (res.data.ifExist) {
        //若是代代回收用户
        wx.navigateTo({
          url: `/pages/recycleCode/recycleCode?qrCode=${res.data?.cardVO?.qrCode}`,
        })
      } else {
        const { loadMiniProgram } = this.data
        if (loadMiniProgram) return

        this.setData({
          loadMiniProgram: true,
        })
        //不是代代回收用户，跳转代代回收小程序完成注册
        wx.navigateToMiniProgram({
          appId: 'wx1932484528bcb05a',
          path: '',
          envVersion: 'release',
          extraData: {
            source: 'QD000001',
          },
          fail: (error) => {
            if (error?.errMsg !== 'navigateToMiniProgram:fail cancel') {
              wx.showToast({
                title: '跳转失败，请重试',
                icon: 'none',
              })
            }
          },
          complete: () => {
            this.setData({
              loadMiniProgram: false,
            })
          },
        })
      }
    } else {
      setStorage('redirectPath', '/pages/mine/mine')
      const userInfo = await app.login()
      this.setData({
        userInfo,
        isLogin: app.isLogin(),
      })
    }
  },
  // 联系我们
  contactUs() {
    this.serviceModal.show()
  },
  // 联系我们-保存图片
  handleSavePhoto() {
    wx.getImageInfo({
      src: this.data.serviceQrcode,
      success: function (sres) {
        // 调用系统方法，下载图片并保存
        getUserPermissions(
          'writePhotosAlbum',
          (res) => {
            if (res) {
              wx.showToast({
                title: '保存成功',
                icon: 'success',
              })
            } else {
              wx.showToast({
                title: '保存失败',
                icon: 'error',
              })
            }
          },
          { filePath: sres.path }
        )
      },
    })
  },
  // 用户点击右上角分享
  onShareAppMessage(e) {
    return shareOptions('default', e)
  },
  /**
   * 页面滚动
   */
  onPageScroll(e) {
		const top = e.scrollTop
		this.setData({
			scrollTop: top*2
		})
  },
  // 拨打电话
  call() {
    wx.makePhoneCall({
      phoneNumber: '0371-53376036'
    })
  },
})
